// pages/user/user.js
import {
    Order
} from './myOrder-model.js'
const app = getApp()
const order = new Order()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        wxUid: '',
        storeNo: '',
        employeNo: '',
        nowId: 1,
        orderList: [],
        deliveryList: [],
        notPayList: [],
        acceptList: [],
        hasMore: false,
        page: 1,
        noneData: false,
        threeOrderCount: null,
        allowClick: true,
        soldoutList: null,
        loadDone: false,
        nowSwiper: 2,
        swiperDown: false,
        needShow:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let current = options.current
        wx.showLoading({
            title: '加载中',
        })
        this.setData({
            storeNo: wx.getStorageSync('storeNo'),
            wxUid: wx.getStorageSync('wxUid'),
            nowSwiper: current
        })
        this.commonRequest(current == 0 ? 'W' : (current == 1 || current == 2 ? 'S' : ''),
            current == 0 ? '' : (current == 1 ? 'LW' : (current == 2 ? 'LU' : '')), '')
    },
    //   按钮点击切换
    tabChange(e) {
        var num = e.currentTarget.dataset.num
        this.setData({
            nowSwiper: num,
        })
    },
    //   左右切换
    swiperChange(e) {
        console.log(e.detail.current)
        let current = e.detail.current
        this.setData({
            nowSwiper: current,
            page: 1,
            swiperDown: false,
        })
        wx.showNavigationBarLoading()
        this.commonRequest(current == 0 ? 'W' : (current == 1 || current == 2 ? 'S' : ''),
            current == 0 ? '' : (current == 1 ? 'LW' : (current == 2 ? 'LU' : '')), 'pulldown')
    },
    //   公共的请求
    commonRequest(orderStatus, logisticStatus, pulldown) {
        // console.log(orderStatus, logisticStatus)
        let {
            page,
            userInfo,
            orderList,
            wxUid,
            notPayList,
            deliveryList,
            nowSwiper
        } = this.data
        let timer = null
        let params = {
            "data": {
                orderStatus,
                "page": '' + page,
                logisticStatus
            }
        }
        this.commonGetOrderCount()
        order.getOrder(params, res => {
            this.setData({
                swiperDown: true
            })
            if (res.status) {
                wx.hideLoading()
                wx.stopPullDownRefresh()
                wx.hideNavigationBarLoading()
                res.data.forEach(val => {
                    val.update_time = order.formate(val.update_time,'yyyy.MM.dd hh:mm:ss')
                    // val.expire = order.conutdown(val.expire_time)
                    let nowPrice
                    if (val.couponAmount) {
                        nowPrice = (Number(val.price) * 100 + Number(val.postage) * 100 - Number(val.couponAmount) * 100) / 100
                    } else {
                        nowPrice = (Number(val.price) * 100 + Number(val.postage) * 100) / 100
                    }
                    val.price = nowPrice
                    switch (val.order_status) {
                        case 'S':
                            val.orderStatusText = '支付成功';
                            break
                        case 'Q':
                            val.orderStatusText = '已取消';
                            break
                        case 'W':
                            val.orderStatusText = '待支付';
                            break
                        case 'F':
                            val.orderStatusText = '支付失败';
                            break
                        case 'RW':
                            val.orderStatusText = '申请退款';
                            break
                        case 'RU':
                            val.orderStatusText = '退款中';
                            break
                        case 'RS':
                            val.orderStatusText = '已退款';
                            break
                        case 'C':
                            val.orderStatusText = '已完成';
                            break
                        case 'RF':
                            val.orderStatusText = '退款失败';
                            break
                        case 'AU':
                            val.orderStatusText = '退款审核中';
                            break
                    }
                })
                this.commonSet(res, pulldown)

                if (orderStatus === 'W') {
                    clearInterval(timer)
                    this.countDown()
                    timer = setInterval(() => {
                        this.countDown()
                    }, 1000)
                }
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
                wx.stopPullDownRefresh()
            }
        })
    },
    //   公共方法，控制列表和loadmore，空空如也情况
    commonSet(res, pulldown) {
        let {
            orderList,
            notPayList,
            deliveryList,
            acceptList,
            nowSwiper
        } = this.data
        let list = nowSwiper == 0 ? notPayList : (nowSwiper == 1 ? deliveryList : (nowSwiper == 2 ? acceptList : orderList));
        if (res.total > list.length && pulldown !== 'pulldown') {
            list = [...list, ...res.data]
            if (nowSwiper == 0) {
                this.setData({
                    notPayList: list
                })
            } else if (nowSwiper == 1) {
                this.setData({
                    deliveryList: list
                }) 
            } else if( nowSwiper == 2){
                this.setData({
                    acceptList: list
                })
            } else if (nowSwiper == 3) {
                this.setData({
                    orderList: list
                })
            }
            this.setData({
                hasMore: true,
                loadDone: true
            })
        } else if (pulldown == 'pulldown') {
            list = res.data
            if (nowSwiper == 0) {
                this.setData({
                    notPayList: list
                })
            } else if (nowSwiper == 1) {
                this.setData({
                    deliveryList: list
                })
            } else if (nowSwiper == 2) {
                this.setData({
                    acceptList: list
                })
            } else if (nowSwiper == 3){
                this.setData({
                    orderList: list
                })
            }
            this.setData({
                hasMore: true,
                loadDone: true
            })
        } else {
            this.setData({
                hasMore: false,
                loadDone: true
            })
        }
        if (res.total == list.length) {
            this.setData({
                hasMore: false,
                loadDone: true
            })
        }
        if (res.total == 0) {
            this.setData({
                noneData: true,
                hasMore: false,
                loadDone: true
            })
        }
    },
    // 定时器
    countDown() {
        let {
            notPayList
        } = this.data
        notPayList.forEach((val) => {
            val.expire = order.conutdown(val.expire_time)
        })
        this.setData({
            notPayList
        })
    },
    //   跳转详情
    jumpDetail(e) {
        let {
            storeNo
        } = this.data;
        let id = order.getDataSet(e, "id");
        wx.navigateTo({
            url: '/pages/orderDetail/orderDetail?orderId=' + id + '&storeNo=' + storeNo,
        })
    },

    //   删除订单
    deleteOrder(e) {
        var id = e.currentTarget.dataset.id
        let that = this
        wx.showModal({
            title: '提示',
            content: '确认删除该订单吗？',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    let params = {
                        "data": {
                            "orderId": "" + id
                        }
                    }
                    wx.showLoading({
                        title: '加载中',
                    })
                    order.deleteOrder(params, res => {
                        if (res.status) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onShow()
                                    }, 1500)
                                }
                            })
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    trace(e) {
        var id = e.currentTarget.dataset.id
        var addressId = e.currentTarget.dataset.address
        wx.navigateTo({
            url: '/pages/orderTrace/orderTrace?addressId=' + addressId + '&orderId=' + id
        })
    },
    //立即支付
    pay(e) {
        console.log(e)
        let that = this
        var dataset = e.currentTarget.dataset
        var id = dataset.id
        var addressId = dataset.address
        let orderList = this.data.orderList
        let allowClick = this.data.allowClick
        console.log(id, addressId)
        let wxuid = wx.getStorageSync('wxUid');

        this.setData({
            allowClick: false
        })
        wx.showLoading({
            title: '加载中',
        })
        //   查询订单地址是否有效
        order.getUserAddressById({
            "data": {
                id: '' + addressId
            }
        }, res => {
            if (res.status) {
                if (!allowClick) {
                    console.log('多点拦截');
                    return
                }
                //   如果地址关联了并且状态不是删除的状态就可以发起支付
                if (addressId && res.data.status != 1) {
                    let getAddress = res.data
                    let params = {
                        data: {
                            "wxuid": wxuid,
                            "orderId": id,
                            "contacts": getAddress.contacts,
                            "mobilePhone": getAddress.mobilePhone,
                            "detailedAddress": getAddress.detailedAddress,
                            "tradeType": "JSAPI"
                        }
                    }
                    console.log(params)

                    order.wxPay(params, res => {
                        wx.hideLoading()
                        if (res.status) {
                            let data = res.data
                            if (data.couponDirectPay === 'SUCCESS') {
                                wx.showToast({
                                    title: '支付成功',
                                })
                                order.reduceGoodsStock({
                                    "data": {
                                        orderId: id,
                                        formId: e.detail.formId
                                    }
                                }, reduce => {
                                    if (that.data.nowSwiper == 0){
                                        that.onShow()
                                    }
                                    orderList.forEach((val, i) => {
                                        if (val.id == id) {
                                            let orderList = 'orderList[' + i + '].order_status'
                                            that.setData({
                                                [orderList]: 'S',
                                                allowClick: true
                                            })
                                        }
                                    })
                                })
                                return
                            }
                            console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign, data.stockList)
                            if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {

                                console.log('success')
                                wx.requestPayment({
                                    'timeStamp': '' + data.miniTimeStamp,
                                    'nonceStr': '' + data.miniNonceStr,
                                    'package': 'prepay_id=' + data.prepay_id,
                                    'signType': 'MD5',
                                    'paySign': '' + data.miniPaySign,
                                    'success': function (result) {
                                        console.log('pay', result)
                                        order.reduceGoodsStock({
                                            "data": {
                                                orderId: id,
                                                formId: e.detail.formId
                                            }
                                        }, reduce => {
                                            orderList.forEach((val, i) => {
                                                if (val.id == id) {
                                                    let orderList = 'orderList[' + i + '].order_status'
                                                    that.setData({
                                                        [orderList]: 'S',
                                                        allowClick: true
                                                    })
                                                }
                                            })
                                        })
                                        app.aldstat.sendEvent('全部订单去付款', data.employeNo);
                                    },
                                    'fail': function (result) {
                                        that.setData({
                                            allowClick: true
                                        })
                                    }
                                })
                            } else if (data.stockList && data.stockList.length > 0) {
                                console.log(data.stockList)
                                this.setData({
                                    soldoutList: data.stockList,
                                    allowClick: true
                                })
                            }
                        } else {
                            wx.showToast({
                                title: '服务器错误',
                                icon: 'none'
                            })
                            this.setData({
                                allowClick: true
                            })
                        }
                    })
                } else {
                    let {
                        storeNo
                    } = this.data;
                    wx.hideLoading()
                    console.log('无地址关联')
                    wx.navigateTo({
                        url: '/pages/orderDetail/orderDetail?orderId=' + id + '&storeNo=' + storeNo,
                    })
                    this.setData({
                        allowClick: true
                    })
                }

            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    vipPay(e) {
        if (wx.getStorageSync('userStatus') == 1) {
            wx.showToast({
                title: '您已经是会员!',
            })
            return
        }
        console.log(e)
        let that = this
        var dataset = e.currentTarget.dataset
        var id = dataset.id
        var addressId = dataset.address
        let orderList = this.data.orderList
        let allowClick = this.data.allowClick
        console.log(id, addressId)
        let wxuid = wx.getStorageSync('wxUid');

        this.setData({
            allowClick: false
        })
        if (!allowClick) {
            console.log('多点拦截');
            return
        }
        wx.showLoading({
            title: '加载中',
        })

        let params = {
            data: {
                "wxuid": wxuid,
                "orderId": id,
            }
        }
        console.log(params)

        order.doUnifiedOrderForRechargeMember(params, res => {
            wx.hideLoading()
            if (res.status) {
                let data = res.data
                console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign, data.stockList)
                if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {

                    console.log('success')
                    wx.requestPayment({
                        'timeStamp': '' + data.miniTimeStamp,
                        'nonceStr': '' + data.miniNonceStr,
                        'package': 'prepay_id=' + data.prepay_id,
                        'signType': 'MD5',
                        'paySign': '' + data.miniPaySign,
                        'success': function (result) {
                            console.log('pay', result)
                            wx.setStorageSync('userStatus', 1);
                            wx.showToast({
                                title: '购买会员成功',
                            })
                            setTimeout(() => {
                                that.onShow()
                            }, 1500)

                        },
                        'fail': function (result) {
                            that.setData({
                                allowClick: true
                            })
                        }
                    })
                } else if (data.stockList && data.stockList.length > 0) {
                    console.log(data.stockList)
                    this.setData({
                        soldoutList: data.stockList,
                        allowClick: true
                    })
                }
            } else {
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
                this.setData({
                    allowClick: true
                })
            }
        })



    },
    soldoutBack() {
        this.setData({
            soldoutList: null,
            allowClick: true
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var {
            page,
            hasMore,
            loadDone,
            nowSwiper
        } = this.data;
        /**
         * 此处加上数据大小的判断
         */
        if (loadDone) {
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 0
            })
            this.setData({
                page: 1,
                allowClick: true,
                swiperDown: false,
                
                
            })
            // this.commonRequest('', '', 'pulldown')
            this.commonRequest(nowSwiper == 0 ? 'W' : (nowSwiper == 1 || nowSwiper == 2 ? 'S' : ''),
                nowSwiper == 0 ? '' : (nowSwiper == 1 ? 'LW' : (nowSwiper == 2 ? 'LU' : '')), 'pulldown')
        }
        this.setData({
            needShow: wx.getStorageSync('needShow') == order.nowV ? false : true  
        })
    },
    showAddAddress() {
        this.setData({
            dialogShow: true
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        var {
            nowSwiper
        } = this.data;


        this.setData({
            page: 1,
        })
        this.commonRequest(nowSwiper == 0 ? 'W' : (nowSwiper == 1 || nowSwiper == 2 ? 'S' : ''),
            nowSwiper == 0 ? '' : (nowSwiper == 1 ? 'LW' : (nowSwiper == 2 ? 'LU' : '')), 'pulldown')

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    scrolltolower() {
        console.log('触底')
        var {
            page,
            hasMore,
            nowSwiper
        } = this.data;
        console.log('bottom', nowSwiper)
        /**
         * 此处加上数据大小的判断
         */
        if (hasMore) {
            this.setData({
                page: page + 1
            })
            this.commonRequest(nowSwiper == 0 ? 'W' : (nowSwiper == 1 || nowSwiper == 2 ? 'S' : ''),
                nowSwiper == 0 ? '' : (nowSwiper == 1 ? 'LW' : (nowSwiper == 2 ? 'LU' : '')), '')
        }
    },
    //    获取各个订单数
    commonGetOrderCount() {
        let parmas = {
            "data": {
                wxUid: this.data.wxUid
            }
        }
        order.getOrderCount(parmas, res => {
            if (res.status) {
                this.setData({
                    threeOrderCount: res.data
                })

            } else {
                wx.hideLoading()
                wx.stopPullDownRefresh()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    // 未发货
    //退款
    wxRefund(e) {
        let that = this
        var dataset = e.currentTarget.dataset
        var id = dataset.id
        let {
            orderList,
            allowClick
        } = this.data
        let params = {
            data: {
                "orderId": id,
                "orderStatus": "AU"
            }
        }
        this.setData({
            allowClick: false
        })

        wx.showModal({
            title: '提示',
            content: '确定退款吗？',
            success(res) {
                if (res.confirm) {
                    wx.showLoading({
                        title: '退款中',
                    })
                    order.wxRefund(params, res => {
                        wx.hideLoading()
                        if (res.status) {
                            console.log(res)
                            wx.showToast({
                                title: '退款申请已提交',
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onShow()
                                    }, 2000)
                                    that.setData({
                                        allowClick: true
                                    })
                                }
                            })
                        } else {
                            that.setData({
                                allowClick: true
                            })
                            wx.hideLoading()
                            wx.showToast({
                                title: '服务器错误',
                                icon: 'none'
                            })
                        }
                    })

                } else {
                    that.setData({
                        allowClick: true
                    })
                }
            }
        })

    },
    // 未付款
    // 取消订单
    cancelOrder(e) {
        var id = e.currentTarget.dataset.id
        let that = this
        wx.showModal({
            title: '提示',
            content: '确认取消该订单吗？',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    let params = {
                        "data": {
                            "orderId": "" + id
                        }
                    }
                    wx.showLoading({
                        title: '加载中',
                    })
                    order.cancelOrder(params, res => {
                        if (res.status) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '取消成功',
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onShow()
                                    }, 1500)
                                }
                            })
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
})